package 线程池;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

/**
 * Created with IntelliJ IDEA.
 * Description:n个任务 分给m个线程
 * User: lenovo
 * Date: 2022-10-05
 * Time: 9:21
 */
class MyTDPool{
    //线程池里的m个线程如何分配n个任务???利用阻塞队列
    private BlockingQueue<Runnable> queue =new LinkedBlockingDeque();
    public void submit(Runnable runnable) throws InterruptedException {//submit用来接收任务
        queue.put(runnable);//将n个任务都放到阻塞队列里
    }
    //创建m个线程,并且扫描阻塞队列
    public  MyTDPool(int m){
        for (int i = 0; i < m; i++) {
            Thread t = new Thread(){
                @Override
                public void run() {
                   while (true){//线程调度很快,这里while循环,每个线程持续扫描阻塞队列
                       try {
                             queue.take().run();//拿出阻塞队列里的任务并且执行run
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
                }
            };
            t.start();
        }
    }

}
public class demo4 {

    public static void main(String[] args) throws InterruptedException {
        MyTDPool pool = new MyTDPool(10);
        for (int i = 0; i < 1000; i++) {
            int idT = i;
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("任务名:"+idT+"  "+"线程名:"+Thread.currentThread().getName());
                }
            });
        }
    }
}
